package com.study.examples.redisson;

import com.study.examples.redisson.service.RedissonService;
import org.redisson.api.RLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName: RedissonApplication
 * @Description:
 * @author: limingxing
 * @Date: 2020-06-19 17:43
 */
@SpringBootApplication
public class RedissonApplication {

    public static void main(String[] args) {
        SpringApplication.run(RedissonApplication.class,args);
    }

    @RestController
    static class TestController{
        private static final Logger log = LoggerFactory.getLogger(TestController.class);

        @Autowired
        private RedissonService redissonService;

        @RequestMapping(value = "/test")
        public void test(String recordId) {

            RLock lock = redissonService.getRLock(recordId);
            try {
                boolean bs = lock.tryLock(5, 6, TimeUnit.SECONDS);
                if (bs) {
                    // 业务代码
                    log.info("进入业务代码: " + recordId);

                    lock.unlock();
                } else {
                    Thread.sleep(300);
                }
            } catch (Exception e) {
                log.error("", e);
                lock.unlock();
            }
        }
    }
}
